/**
 * 绘制图层类
 * 支持在地图上绘制点、线、面等要素
 */

import { Map as OlMap } from 'ol';
import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import { Feature } from 'ol';
import { Geometry, Point, LineString, Polygon, Circle } from 'ol/geom';
import { Draw, Modify, Snap } from 'ol/interaction';
import { BaseLayer } from './BaseLayer';
import { DrawLayerOptions } from '../types';
import { StyleUtil } from '../utils/style';
import { Style } from 'ol/style';

/**
 * 绘制图层类
 */
export class DrawLayer extends BaseLayer {
  /** 图层配置 */
  protected options: DrawLayerOptions;
  /** 矢量数据源 */
  private source: VectorSource<Feature<Geometry>> | null = null;
  /** 绘制交互 */
  private drawInteraction: Draw | null = null;
  /** 编辑交互 */
  private modifyInteraction: Modify | null = null;
  /** 捕捉交互 */
  private snapInteraction: Snap | null = null;

  /**
   * 构造函数
   * @param options 图层配置
   */
  constructor(options: DrawLayerOptions = {}) {
    super(options);
    this.options = {
      drawType: 'Point',
      editable: true,
      deletable: true,
      ...options
    };
  }

  /**
   * 创建图层
   */
  protected createLayer(): void {
    this.source = new VectorSource<Feature<Geometry>>();

    this.layer = new VectorLayer({
      source: this.source,
      style: (feature) => this.getStyle(feature as Feature<Geometry>)
    });

    // 如果允许编辑，添加编辑交互
    if (this.options.editable && this.map) {
      this.modifyInteraction = new Modify({
        source: this.source
      });
      this.map.addInteraction(this.modifyInteraction);

      // 添加捕捉交互
      this.snapInteraction = new Snap({
        source: this.source
      });
      this.map.addInteraction(this.snapInteraction);
    }
  }

  /**
   * 获取要素样式
   * @param feature 要素
   * @returns 样式
   */
  private getStyle(feature: Feature<Geometry>): Style | Style[] {
    const geometry = feature.getGeometry();
    if (!geometry) {
      return new Style();
    }

    if (geometry instanceof Point) {
      return StyleUtil.createCircleStyle({
        radius: 5,
        fillColor: '#3399CC',
        strokeColor: '#fff',
        strokeWidth: 2
      });
    } else if (geometry instanceof LineString) {
      return StyleUtil.createLineStyle({
        color: '#3399CC',
        width: 2
      });
    } else if (geometry instanceof Polygon || geometry instanceof Circle) {
      return StyleUtil.createPolygonStyle({
        fillColor: 'rgba(51, 153, 204, 0.3)',
        strokeColor: '#3399CC',
        strokeWidth: 2
      });
    }

    return new Style();
  }

  /**
   * 开始绘制
   * @param drawType 绘制类型（可选，不传则使用配置的类型）
   */
  startDraw(drawType?: 'Point' | 'LineString' | 'Polygon' | 'Circle'): void {
    if (!this.map || !this.source) {
      throw new Error('Layer not initialized');
    }

    // 停止当前绘制
    this.stopDraw();

    const type = drawType || this.options.drawType || 'Point';
    const geometryType = type === 'Circle' ? 'Circle' : type;

    // 创建绘制交互
    this.drawInteraction = new Draw({
      source: this.source,
      type: geometryType as any
    });

    // 监听绘制完成事件
    this.drawInteraction.on('drawend', (event: any) => {
      const feature = event.feature;
      if (this.options.onDrawEnd) {
        this.options.onDrawEnd(feature);
      }
      this.emit('drawend', feature);
      this.stopDraw();
    });

    this.map.addInteraction(this.drawInteraction);
    this.emit('drawstart', type);
  }

  /**
   * 停止绘制
   */
  stopDraw(): void {
    if (this.map && this.drawInteraction) {
      this.map.removeInteraction(this.drawInteraction);
      this.drawInteraction = null;
    }
  }

  /**
   * 删除要素
   * @param featureId 要素ID
   */
  deleteFeature(featureId: string | number): void {
    if (!this.source || !this.options.deletable) return;

    const feature = this.source.getFeatureById(featureId);
    if (feature && feature instanceof Feature) {
      this.source.removeFeature(feature);
      this.emit('featuredelete', feature);
    }
  }

  /**
   * 清空所有要素
   */
  clearFeatures(): void {
    if (this.source) {
      this.source.clear();
      this.emit('featuresclear');
    }
  }

  /**
   * 获取所有要素
   * @returns 要素数组
   */
  getFeatures(): Feature<Geometry>[] {
    return this.source?.getFeatures() || [];
  }

  /**
   * 根据ID获取要素
   * @param featureId 要素ID
   * @returns 要素
   */
  getFeatureById(featureId: string | number): Feature<Geometry> | null {
    const feature = this.source?.getFeatureById(featureId);
    return feature instanceof Feature ? feature : null;
  }

  /**
   * 设置是否可编辑
   * @param editable 是否可编辑
   */
  setEditable(editable: boolean): void {
    this.options.editable = editable;

    if (!this.map) return;

    if (editable) {
      // 添加编辑交互
      if (!this.modifyInteraction) {
        this.modifyInteraction = new Modify({
          source: this.source!
        });
        this.map.addInteraction(this.modifyInteraction);
      }

      if (!this.snapInteraction) {
        this.snapInteraction = new Snap({
          source: this.source!
        });
        this.map.addInteraction(this.snapInteraction);
      }
    } else {
      // 移除编辑交互
      if (this.modifyInteraction) {
        this.map.removeInteraction(this.modifyInteraction);
        this.modifyInteraction = null;
      }

      if (this.snapInteraction) {
        this.map.removeInteraction(this.snapInteraction);
        this.snapInteraction = null;
      }
    }
  }

  /**
   * 销毁图层
   */
  destroy(): void {
    this.stopDraw();

    if (this.map) {
      if (this.modifyInteraction) {
        this.map.removeInteraction(this.modifyInteraction);
      }
      if (this.snapInteraction) {
        this.map.removeInteraction(this.snapInteraction);
      }
    }

    super.destroy();
  }
}

